package com.junchao.peng.service.impl;

import com.junchao.peng.mapper.UserMapper;
import com.junchao.peng.pojo.User;
import com.junchao.peng.service.EmailService;
import com.junchao.peng.utils.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author dell
 */
@Service("EmailService")
public class EmailServiceImpl implements EmailService {
    final RedisTemplate redisTemplate;
    final UserMapper userMapper;

    JavaMailSenderImpl mailSender;
    SimpleMailMessage message;

    public EmailServiceImpl(RedisTemplate redisTemplate, UserMapper userMapper) {
        this.redisTemplate = redisTemplate;
        this.userMapper = userMapper;
        mailSender = new JavaMailSenderImpl();
        message = new SimpleMailMessage();
    }

    @Override
    public JsonResult sendEmailToAll(Integer userId, String sessionName, String token) {
        if (getToken(token)){
            return new JsonResult("用户未登录",403);
        }
        mailSenderInit(userMapper.selectUserById(userId),sessionName);

        mailSender.send(message);

        return new JsonResult("邮件群发成功");
    }

    private boolean getToken(String token){
        boolean flag = false;
        Object redisCode = redisTemplate.opsForValue().get(token);
        if (redisCode != null){
            flag = true;
        }
        return !flag;
    }

    private void mailSenderInit(User user, String session){
        mailSender.setUsername(user.getEmail());
        mailSender.setPassword(user.getPassword());
        mailSender.setHost("smtp.qq.com");
        mailSender.setPort(-1);
        mailSender.setProtocol("smtp");
        mailSender.setDefaultEncoding("UTF-8");

        message.setSubject("会议通知");
        message.setText(session);
        List<User> users = userMapper.listUser();
        String[] sentTos = new String[users.size()-1];
        int i = 0;
        for (User user1 : users) {
            if (user1.getEmail().equals(user.getEmail())){
                continue;
            }
            sentTos[i++] = user1.getEmail();
        }
        message.setTo(sentTos);
        message.setFrom(user.getEmail());
        message.setCc(user.getEmail());
    }
}
